import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, OnDestroy, OnInit, Optional, ViewChild } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { DA_SERVICE_TOKEN, ITokenService, SocialOpenType, SocialService } from '@delon/auth';
import { SFComponent, SFSchema, SFUISchema, SFStringWidgetSchema } from '@delon/form';
import { SettingsService, _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { NzTabChangeEvent } from 'ng-zorro-antd/tabs';
import { interval } from 'rxjs';
import { finalize, take } from 'rxjs/operators';
import { DunHelper } from 'src/app/shared/components/captcha';
import { EAUserService, EACaptchaService, EAValidateService, EAPlatformService } from 'src/app/shared/services';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  host: {
    '[class.ant-row]': 'true',
    '[class.pro-passport]': 'true'
  }
})
export class UserLoginComponent implements OnInit, OnDestroy {
  @ViewChild('accountSF', { static: false })
  accountSF!: SFComponent;
  @ViewChild('captchaSF', { static: false })
  captchaSF!: SFComponent;
  accountSchema!: SFSchema;
  accountUI!: SFUISchema;
  captchaSchema!: SFSchema;
  captchaUI!: SFUISchema;
  count = 0;
  type = 0;

  isPasswordType = true;
  // vcode = null;

  copyright = '';
  constructor(
    public userSrv: EAUserService,
    private captchaSrv: EACaptchaService,
    private validateSrv: EAValidateService,
    private dunHelper: DunHelper,
    private cdr: ChangeDetectorRef,
    private router: Router
  ) {
    // this.vcode = this.platformSrv.getOperatorCode();
    //  加载copyright信息
    // this.userSrv
    //   .request(this.platformSrv.$api_get_config, {
    //     pageIndex: 1,
    //     pageSize: 999,
    //   })
    //   .subscribe((res: any) => {
    //     this.copyright = res?.records?.find((f: any) => f.configKey === 'website.copyright')?.configValue;
    //     this.imageUrl = res?.records?.find((f: any) => f.configKey === 'platform.saas.logo')?.configValue;
    //   });
  }

  ngOnInit(): void {
    this.initAccountSF();
    this.initCaptchaSF();
  }

  initAccountSF(): void {
    this.accountSchema = {
      properties: {
        username: {
          title: '',
          type: 'string',
          maxLength: 11,
          ui: {
            widget: 'custom',
            size: 'large',
            errors: { required: '请输入手机号', format: '手机号格式错误' }
          }
        },
        password: {
          title: '',
          type: 'string',
          ui: {
            widget: 'custom',
            size: 'large',
            errors: { required: '请输入密码' }
          }
        }
        // sc: {
        //   title: '',
        //   type: 'string',
        //   ui: {
        //     hidden: !!this.vcode,
        //     placeholder: '请输入安全码',
        //     prefixIcon: 'safety',
        //     size: 'large',
        //     errors: {
        //       required: '请输入安全码'
        //     }
        //   } as SFStringWidgetSchema,
        //   default: this.vcode
        // }
      },
      required: ['username', 'password']
    };
    this.accountUI = {
      '*': { spanLabelFixed: 110, grid: { span: 24 } }
    };
  }

  initCaptchaSF(): void {
    this.captchaSchema = {
      properties: {
        phone: {
          title: '',
          type: 'string',
          format: 'mobile',
          maxLength: 11,
          ui: {
            placeholder: '请输入手机号',
            widget: 'custom',
            size: 'large',
            errors: { required: '请输入手机号！', format: '手机号格式错误' }
          }
        },
        smsCode: {
          title: '',
          type: 'string',
          maxLength: 6,
          ui: {
            widget: 'custom',
            size: 'large',
            errors: { required: '请输入验证码！', maxLength: '验证码错误' }
          }
        }
        // sc: {
        //   title: '',
        //   type: 'string',
        //   ui: {
        //     hidden: !!this.vcode,
        //     placeholder: '请输入安全码',
        //     prefixIcon: 'safety',
        //     size: 'large',
        //     errors: {
        //       required: '请输入安全码'
        //     }
        //   } as SFStringWidgetSchema,
        //   default: this.vcode
        // }
      },
      required: ['phone', 'smsCode']
    };
    this.captchaUI = {
      '*': { spanLabelFixed: 110, grid: { span: 24 } }
    };
  }

  /**
   * 获取验证码
   */
  getCaptcha(): void {
    this.captchaSF.getProperty('/phone')?.updateValueAndValidity();
    const result = this.validateSrv.validateMobile(this.captchaSF.value.phone);
    // this.captchaSrv.sendSMSCaptchaByMobile();
    if (result) {
      this.captchaSrv.sendSMSCaptchaByMobile(this.captchaSF.value.phone).subscribe(res => {
        console.log(res);

        if (res.success && res.data.code === '1') {
          this.captchaSrv.msgSrv.success('发送验证码成功');
          this.createInterval();
        }
        // else if (res.status === 503609) {
        //   this.dunHelper.popUp(this.captchaSF.value.phone).subscribe(_ => {
        //     this.createInterval();
        //     this.dunHelper.destory();
        //   });
        // }
        else {
          this.captchaSrv.msgSrv.warning(res.msg);
        }
      });
    }
  }

  /**
   * 登录
   */
  submit(): void {
    console.log(1);
    
   this.userSrv.loginByMobile(this.captchaSF.value.phone, this.captchaSF.value.smsCode, this.captchaSF.value.sc);
    // if (this.type === 0) {
    //   this.accountSF.validator({ emitError: true });
    //   if (!this.accountSF.valid) {
    //     return;
    //   }
    //   this.userSrv.loginByAccount(this.accountSF.value.username, this.accountSF.value.password);
    // } else {
    //   this.captchaSF.validator({ emitError: true });
    //   if (!this.captchaSF.valid) {
    //     return;
    //   }
    //   this.userSrv.loginByMobile(this.captchaSF.value.phone, this.captchaSF.value.smsCode, this.captchaSF.value.sc);
    // }
    // this.router.navigateByUrl('/');
    /*  if (!this.accountSF.valid && !this.captchaSF.valid) {
       return;
     }

     Object.prototype.hasOwnProperty.call(value, 'username')
       ? this.userSrv.loginByAccount(value.username, value.password)
       : this.userSrv.loginByCaptcha(value.phone, value.smsCode); */
  }

  switch(ret: any) {
    this.type = ret.index;
  }

  ngOnDestroy(): void {}

  changeInputType(a: any) {
    console.log(a);
  }

  private createInterval() {
    this.count = 59;
    interval(1000)
      .pipe(take(60))
      .subscribe(x => {
        this.count = 59 - (x + 1);
        this.cdr.detectChanges();
      });
  }
}
